<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Laravel\Scout\Searchable;

class Coupon extends Model
{
    use Searchable;

    //
    use softDeletes;
    public $typeText = [
        '2' => '美食',
        '3' => '娱乐',
        '4' => '酒店',
        '5' => '服务',
        '6' => '教育',
        '7' => '丽人',
        '8' => '其他',
    ];
    public $preferText = [
        '1' => '元',
        '2' => '折',
    ];
    public $prefeText = [
        '1' => '减免',
        '2' => '折扣',
    ];
    public $weekText = [
        '1' => '周一',
        '2' => '周二',
        '3' => '周三',
        '4' => '周四',
        '5' => '周五',
        '6' => '周六',
        '7' => '周日',
        '8' => '工作日',
        '9' => '周末',
        '10' => '每天',
    ];
    public $weekKey = [
        '0'=>10,
        '1'=>8,
        '2'=>9
    ];
    public $timeText = [
        '1' => '上午',
        '2' => '下午',
        '3' => '晚上',
        '4' => '全天',
    ];
    public $timeKey = [
        '0'=>4,
        '1'=>1,
        '2'=>2,
        '3'=>3
    ];
    public $statusText = [
        true => '显示',
        false => '隐藏',
    ];
    public $verifyText = [
        '1' => '待审核',
        '2' => '已审核',
        '3' => '驳回',
        '4' => '垃圾信息',
    ];

    // 获取用户
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    # 获取评论
    public function comments()
    {
        return $this->hasMany(Comments::class, 'coupon_id');
    }

    public function toSearchableArray()
    {
        return [
            'name' => $this->name,
            'type' => $this->typeText[$this->type],
            'address' => $this->address,
            'phone' => $this->phone,
            'verify' => $this->verify,
            'status' => $this->status,
            'content' => $this->content,
            'count' => (bool)($this->count - $this->use_count) + 0
        ];
    }

    // 获取图片完整路径
    public function getImgAttribute($img)
    {
        if (!filter_var($img, FILTER_VALIDATE_URL))
            return env('OSS_ENDPOINT') . env('OSS_PREFIX') . $img;
        return $img;
    }

    # 计算距离
    public function distance($lng, $lat, $item)
    {
        $tmpNum = get_lng_and_lat_distance($item->latitude, $item->longitude, $lat, $lng);
        //$item->distanceNum = $tmpNum;
        $distance = get_distance_text($tmpNum);
        return $distance;
    }

    /**
     * 获取 最近的优惠券列表
     * @param $lng
     * @param $lat
     * @param array $where
     * @return bool
     */
    public function getNearLists($lng, $lat, $where = [], $distance = 50000)
    {
        $offsets = get_lng_and_lat_deviation($lng, $lat, $distance);

        if (\App::environment('local', 'staging')) {
            $res = $this
                ->where($where)
                ->get();
        } else {
            $res = $this
                ->whereBetween('longitude', $offsets['lng'])
                ->whereBetween('latitude', $offsets['lat'])
                ->where($where)
                ->get();
        }

        if (!$res->count())
            return collect();
        $res->map(function ($item) use ($lng, $lat) {
            $tmpNum = get_lng_and_lat_distance($item->latitude, $item->longitude, $lat, $lng);
            $item->distanceNum = $tmpNum;
            $item->distance = get_distance_text($tmpNum);
        });
        return $res->sortBy('distanceNum');
    }

    /**
     * 计算某个优惠券已领人数
     */
    public function lingnum($id)
    {
        $ordersNum = app(Order::class)->where([
            ['coupon_id', $id],
            ['status', 2]
        ])->count();
        return $ordersNum;
    }

    // 判断是否已过期
    public function isOverTime($end)
    {
        if (empty($end)) {
            return false;
        }
        $date = date('Y-m-d', time());
        # 已过期，返回2
        if ($end < $date) {
            return 2;
        }
        return false;
    }

    # 转换日期格式（用'.'隔开）
    public function dateChange($date)
    {
        $arr = explode('-', $date);
        return $arr[0] . '.' . $arr[1] . '.' . $arr[2];
    }

    # 转换日期格式（用'月,日'隔开）
    public function dateTotext($date)
    {
        $arr = explode('-', $date);
        return str_replace(0,'',$arr[1]) . '月' . $arr[2] . '日';
    }

    # 判断优惠券是否达到最大领取限制
    # $times : 优惠券的最大领取个数
    public function isLimit($coupon_id, $user_id, $times)
    {
        $orders = app(Order::class)->where([
            ['user_id', $user_id],
            ['coupon_id', $coupon_id],
            ['status', 2]
        ])->count();
        //dd($orders);
        if ($orders >= $times) {
            return true;
        }
        return false;
    }

    # 判断用户是否已领取该优惠券
    public function isBuy($coupon_id, $openid)
    {
        $userInfo = User::where(['openid'=>$openid])->first();
        $orderInfo = Order::where([
            ['user_id',$userInfo['id']],
            ['coupon_id',$coupon_id],
            ['status',2]
        ])->first();
        if($orderInfo){
            if($orderInfo['type'] == 1){
                return 1;
            }
            if($orderInfo['type'] == 2){
                return 2;
            }
        }else {
            return 0;
        }
    }

}
